﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Common;
using DbControl;
using Models;

namespace CentralMonitoring
{
    /// <summary>
    /// 数据查询窗体
    /// </summary>
    public partial class ViewForm : Form
    {
        public string mdeviceName;
        public ViewForm()
        {
            InitializeComponent();
        }
        #region treeview
        private void InitTree()
        {
            this.treeView1.Nodes.Clear();
            DataTable dt = OprDevice.GetdevicesTree();
            if (dt != null && dt.Rows.Count > 0)
            {
                DataView dv = dt.DefaultView;
                dv.Sort = "parentid ASC";
                DataRowView[] arrDRV = dv.FindRows("0");
                if (arrDRV.Length == 0)
                    return;
                TreeNode tnNew = null;
                treeView1.BeginUpdate();
                foreach (DataRowView drv in arrDRV)
                {
                    tnNew = this.treeView1.Nodes.Add(drv["device_name"].ToString());
                    tnNew.Tag = drv.Row["id"];
                    CreateTreeNode(ref tnNew, dv);
                }
                treeView1.EndUpdate();
                treeView1.ExpandAll();
            }
        }
        private void CreateTreeNode(ref TreeNode tnParent, DataView dv)
        {
            DataRowView[] arrDrv = dv.FindRows(tnParent.Tag);
            if (arrDrv.Length == 0)
                return;
            TreeNode tnNew = null;
            foreach (DataRowView drv in arrDrv)
            {
                tnNew = tnParent.Nodes.Add(drv.Row["device_name"].ToString());
                tnNew.Tag = drv.Row["ID"].ToString();
                CreateTreeNode(ref tnNew, dv);

            }
        }
        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point clickPoint = new Point(e.X, e.Y);
                TreeNode currentNode = treeView1.GetNodeAt(clickPoint);
                if (currentNode != null)
                {
                    treeView1.SelectedNode = currentNode;
                }
                else
                {
                    treeView1.SelectedNode = null;
                }
            }

        }
        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            int nodeId;
            if (e.Node.Nodes.Count > 0)
            {
                e.Node.Expand();
                nodeId = int.Parse(e.Node.Tag.ToString());
                treeView1.SelectedNode = e.Node;
                textBoxDevice.Text = e.Node.Text;
                RefreshGrid();              
            }
            else
            {
                nodeId = int.Parse(e.Node.Tag.ToString());
                treeView1.SelectedNode = e.Node;
                textBoxDevice.Text = e.Node.Text;
                RefreshGrid();
              
            }           
        }

        #endregion
        private void buttonFind_Click(object sender, EventArgs e)
        {
            RefreshGrid();
        }       
        private void ViewForm_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            dateTimePicker开始时间.Value = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
            dateTimePicker终止时间.Value = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));
            InitTree();      
            RefreshGrid();
          
            this.StatusLabel0.Text = string.Format("系统时间：{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }
        private void RefreshGrid()
        {
            string filter = "";            
            if (!string.IsNullOrEmpty(textBoxDevice.Text))
            {
                filter =textBoxDevice.Text;
            }
                     
            DataTable ds = OprUI.GetSensorDatasByDeviceName(dateTimePicker开始时间.Value, dateTimePicker终止时间.Value,filter);
            if (ds != null)
            {
                this.dataGridView1.DataSource = ds;
                dataGridView1.Columns["id"].Visible = false;                
                dataGridView1.Columns["device_name"].HeaderText = "设备名称";
                dataGridView1.Columns["device_code"].HeaderText = "设备编码";
                dataGridView1.Columns["sensor_sn"].HeaderText = "终端码";
                dataGridView1.Columns["temper"].HeaderText = "温度";                
                dataGridView1.Columns["diel"].HeaderText = "介电常数";
                dataGridView1.Columns["vis"].HeaderText = "粘度";
                dataGridView1.Columns["vis40"].Visible = false; ;
                dataGridView1.Columns["dens"].HeaderText = "密度";
                dataGridView1.Columns["ppm"].HeaderText = "水分";
                dataGridView1.Columns["aw"].HeaderText = "水活性";
                dataGridView1.Columns["create_time"].HeaderText = "时间";
                dataGridView1.Columns["create_time"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
                dataGridView1.Columns["create_time"].Width = 120;
                dataGridView1.Columns["fe1"].HeaderText = "70-90μm(fe1)";
                dataGridView1.Columns["fe2"].HeaderText = "90-110μm(fe2)";
                dataGridView1.Columns["fe3"].HeaderText = "110-140μm(fe3)";
                dataGridView1.Columns["fe4"].HeaderText = "140-170μm(fe4)";
                dataGridView1.Columns["fe5"].HeaderText = "170-200μm(fe5)";
                dataGridView1.Columns["fe6"].HeaderText = "200-230μm(fe6)";
                dataGridView1.Columns["fe7"].HeaderText = "230-280μm(fe7)";
                dataGridView1.Columns["fe8"].HeaderText = "280-350μm(fe8)";
                dataGridView1.Columns["fe9"].HeaderText = "350-420μm(fe9)";
                dataGridView1.Columns["fe10"].HeaderText = ">420μm(fe10)";
                dataGridView1.Columns["nfe1"].HeaderText = "265-530μm(nfe1)";
                dataGridView1.Columns["nfe2"].HeaderText = "530-1060μm(nfe2)";
                dataGridView1.Columns["nfe3"].HeaderText = "1060-2120μm(nfe3)";               
                dataGridView1.Columns["nfe4"].HeaderText = ">2120μm(nfe4)";
                dataGridView1.Columns["class6"].HeaderText = "ISO等级";
                dataGridView1.Columns["class_total"].HeaderText = "NAS等级";
                dataGridView1.ReadOnly = true;               
                dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;               
                dataGridView1.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
                dataGridView1.AllowUserToAddRows = false;
                dataGridView1.AllowUserToDeleteRows = false;
                dataGridView1.AllowUserToOrderColumns = true;               
                dataGridView1.ColumnHeadersHeight = 30;
                //dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;              
                dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                dataGridView1.ScrollBars = ScrollBars.Both;
            }

        }

        private void buttonExp_Click(object sender, EventArgs e)
        {
            try
            {
                int code = ExportToExcel.Export(this.dataGridView1);
                switch (code)
                {
                    case -1: MessageBox.Show("保存EXCEL失败，详细原因查看日志(Log)文件"); break;
                    case 1: MessageBox.Show(this, "保存EXCEL成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); break;
                    case 0: break;
                    default: break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据导出失败:" + ex.ToString());
            }
        }
        private void Export(DataTable dt)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "Execl files (*.xls)|*.xls";
            dlg.FilterIndex = 0;
            dlg.RestoreDirectory = true;
            dlg.CreatePrompt = true;
            dlg.Title = "保存为Excel文件";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                Stream myStream;
                myStream = dlg.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));//.GetEncoding(-0));
                string columnTitle = "";
                try
                {


                    //DataTable table = BearDataOpr.SelectFromSql(sql);
                    DataTable table = dt.Copy();
                    //DataTable dt = table.Copy();

                    //写入列标题     
                    for (int i = 0; i < this.dataGridView1.ColumnCount; i++)
                    {
                        columnTitle += dataGridView1.Columns[i].HeaderText;
                        columnTitle += "\t";
                    }
                    sw.WriteLine(columnTitle);
                    DateTime dtValue;
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        for (int j = 0; j < table.Columns.Count; j++)
                        {

                            if (dt.Rows[i][j] != DBNull.Value && table.Columns[j].Caption.ToString().Contains("时间"))
                            {
                                if (dt.Rows[i][j] != null && DateTime.TryParse(dt.Rows[i][j].ToString(), out dtValue))
                                    dt.Rows[i][j] = Convert.ToDateTime(dt.Rows[i][j]).ToString("yyyy-MM-dd HH:mm:ss");
                                else
                                    dt.Rows[i][j] = "";
                            }

                        }
                    }

                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        string columnValue = "";
                        for (int k = 0; k < dt.Columns.Count; k++)
                        {
                            columnValue += dt.Rows[j][k].ToString().Trim();
                            columnValue += "\t";
                        }
                        sw.WriteLine(columnValue);
                    }

                    sw.Close();
                    myStream.Close();
                    MessageBox.Show(this, "保存EXCEL成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("保存EXCEL失败，详细原因查看日志(Log)文件");
                    lLogWrite.WriteLog("保存EXCEL失败" + ex.ToString());
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.StatusLabel0.Text = string.Format("系统时间：{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }
}
